package icu.cocoon.sms.service.impl;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import icu.cocoon.sms.entity.SendCodeLog;
import icu.cocoon.sms.properties.AliyunConfig;
import icu.cocoon.sms.service.SendCodeLogService;
import icu.cocoon.sms.service.SmsService;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author xce
 * @date 2020/3/19  16:48
 */
@Slf4j
@Service
public class AliyunSmsService implements SmsService {

  @Resource
  private AliyunConfig aliyunConfig;

  @Resource
  private SendCodeLogService sendCodeLogService;

  private DefaultAcsClient client;

  @PostConstruct
  private void postConstruct() {
    DefaultProfile profile = DefaultProfile
        .getProfile(aliyunConfig.getRegionId(), aliyunConfig.getAccessKeyId(), aliyunConfig.getSecret());
    this.client = new DefaultAcsClient(profile);
  }


  @Async
  @Override
  public void sendSmsCode(String phone, String code) throws ClientException, JsonProcessingException {
    CommonRequest request = new CommonRequest();
    request.setMethod(MethodType.POST);
    request.setDomain("dysmsapi.aliyuncs.com");
    request.setVersion("2017-05-25");
    request.setAction("SendSms");
    request.putQueryParameter("RegionId", "cn-hangzhou");
    request.putQueryParameter("PhoneNumbers", phone);
    request.putQueryParameter("SignName", "MyBlog");
    request.putQueryParameter("TemplateCode", "SMS_186395936");
    request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");

    CommonResponse response = this.client.getCommonResponse(request);
    ObjectMapper objectMapper = new ObjectMapper();
    Map json = objectMapper.readValue(response.getData(), Map.class);
    log.info("sendSmsCode：phone:{} 返回结果：{}", phone, json.toString());

    SendCodeLog sendCodeLog = new SendCodeLog();
    sendCodeLog.setPhone(phone);
    sendCodeLog.setResponseData(response.getData());
    sendCodeLog.setMessage(json.get("Message").toString());
    sendCodeLog.setCode(json.get("Code").toString());
    sendCodeLog.setRequestId(json.get("RequestId").toString());
    sendCodeLogService.create(sendCodeLog);
  }

}
